<script setup>
import { ref, onMounted } from 'vue'
import { User } from '@vicons/fa'
import { MdLogOut } from '@vicons/ionicons4'
import { useMainStore } from '../pinia.js'

console.log('LoginButton.vue script loaded at:', new Date().toISOString())

const mainStore = useMainStore()

const emit = defineEmits(['message'])

const showLoginModal = ref(false)
const loginLoading = ref(false)

const username = ref('')
const password = ref('')

onMounted(async () => {
  console.log('LoginButton onMounted - Restoring user state from localStorage')
  username.value = localStorage.getItem('username')
  const storedSgsToken = localStorage.getItem('sgsToken')
  const storedAuthToken = localStorage.getItem('authToken')
  const storedUserRole = localStorage.getItem('userRole') || 'user'
  const storedDisplayUsername = localStorage.getItem('displayUsername') || ''
  
  console.log('Stored values:', {
    sgsToken: storedSgsToken,
    authToken: storedAuthToken,
    userRole: storedUserRole,
    displayUsername: storedDisplayUsername
  })
  
  mainStore.sgsToken = storedSgsToken
  mainStore.authToken = storedAuthToken
  mainStore.userRole = storedUserRole
  mainStore.displayUsername = storedDisplayUsername
  
  console.log('MainStore state after restoration:', {
    userRole: mainStore.userRole,
    isAdmin: mainStore.isAdmin,
    canAccessAdminFeatures: mainStore.canAccessAdminFeatures
  })
  
  if (mainStore.sgsToken && mainStore.authToken) {
    try {
      const { success, userInfo } = await mainStore.checkAuth()
      if (success) {
        mainStore.displayUsername = userInfo.username
        localStorage.setItem('displayUsername', userInfo.username)
      } else {
        throw new Error('Token expired')
      }
    } catch {
      mainStore.clearUserInfo()
      localStorage.removeItem('sgsToken')
      localStorage.removeItem('authToken')
      localStorage.removeItem('userRole')
      localStorage.removeItem('displayUsername')
      showLoginModal.value = true
    }
  } else {
    showLoginModal.value = true
  }
})

const handleLogin = async () => {
  loginLoading.value = true
  localStorage.setItem('username', username.value)
  const response = await fetch('/auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: username.value,
      password: password.value
    })
  })
  const responseData = await response.json()
  console.log('Login response data:', responseData)
  const { success, token, uname, sgsToken, role, info } = responseData
  if (success) {
    console.log('Setting user info with role:', role)
    // 使用新的setUserInfo方法设置用户信息
    mainStore.setUserInfo({
      token,
      uname,
      sgsToken,
      role
    })
    
    // 保存到localStorage
    localStorage.setItem('authToken', token)
    localStorage.setItem('sgsToken', sgsToken)
    localStorage.setItem('displayUsername', uname)
    localStorage.setItem('userRole', role || 'user')
    
    loginLoading.value = false
    showLoginModal.value = false
    emit('message', 'success', `登录成功 (${role === 'admin' ? '管理员' : '普通用户'})`)
  } else {
    loginLoading.value = false
    emit('message', 'warning', info)
  }
}

const isUserButtonHovered = ref(false)
const logout = () => {
  mainStore.clearUserInfo()
  localStorage.removeItem('sgsToken')
  localStorage.removeItem('authToken')
  localStorage.removeItem('userRole')
  localStorage.removeItem('displayUsername')
  showLoginModal.value = true
  emit('message', 'success', 'Logout success')
}
</script>

<template>
  <n-float-button
    :right="16" :top="16"
    :title="mainStore.displayUsername"
    @mouseover="isUserButtonHovered = true" @mouseleave="isUserButtonHovered = false" @click="logout"
  >
    <n-icon>
      <MdLogOut v-if="isUserButtonHovered"/>
      <User v-else/>
    </n-icon>
  </n-float-button>
  <n-modal
    v-model:show="showLoginModal"
    :close-on-esc="false"
    :mask-closable="false"
    class="login-modal"
  >
    <n-card
      title="用户登录 (APAC账号)"
      :bordered="false"
      size="medium"
    >
      <n-alert type="info" style="margin-bottom: 16px;">
        请使用您的APAC域账号登录
      </n-alert>
      <n-form label-placement="left" label-width="auto">
        <n-form-item label="用户名">
          <n-input class="input-line" v-model:value="username" type="text" placeholder="apac\user_name" spellcheck="false"></n-input>
        </n-form-item>
        <n-form-item label="密码">
          <n-input class="input-line" v-model:value="password" type="password" show-password-on="click" @keyup.enter="handleLogin"></n-input>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space align="center" justify="center">
          <n-button @click="handleLogin" :loading="loginLoading" type="primary" secondary strong style="width: 16em;">登录</n-button>
        </n-space>
      </template>
    </n-card>
  </n-modal>
</template>

<style lang="stylus">
.login-modal
  width: 27em
  .n-card__content
    padding-bottom: 0
    input
      font-size: 13px!important
</style>